const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../service/user.service");

const {
  userFormDataError,
  userRepetitionError,
  userLoginError,
} = require("../constant/errorType");

// 表单数据校验
const verifyUserFormData = async (ctx, next) => {
  const { userName, password } = ctx.request.body;

  if (!userName || !password)
    return ctx.app.emit("error", userFormDataError, ctx);

  await next();
};

// 是否重复校验
const verifyUserRepetition = async (ctx, next) => {
  const { userName: user_name } = ctx.request.body;

  const res = await getUserInfo({ isRegister: true, user_name }, ctx);
  if (res) return ctx.app.emit("error", userRepetitionError, ctx);

  await next();
};

// 加密
const encodePassword = async (ctx, next) => {
  const { password } = ctx.request.body;
  const salt = bcrypt.genSaltSync(10);
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;

  await next();
};

// 校验登录
const verifyLogin = async (ctx, next) => {
  const { userName: user_name, password } = ctx.request.body;
  const res = await getUserInfo({ user_name }, ctx);
  if (!res || !bcrypt.compareSync(password, res.password))
    return ctx.app.emit("error", userLoginError, ctx);

  await next();
};

module.exports = {
  verifyUserFormData,
  verifyUserRepetition,
  encodePassword,
  verifyLogin,
};
